package com.binc.testspring.common.utils.goodStuff;

import org.junit.Test;

/**
 * 驼峰相关的工具
 */
public class CamelCaseUtil {

    private static final char SEPARATOR = '_';

    /**
     * 驼峰名称变成 带有下环线的名称
     *  userName  变 user_name
     * @param s
     * @return
     */
    public static String toUnderlineName(String s) {
        if (null == s) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        boolean upperCase = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            boolean nextUpperCase = true;
            if (i < (s.length() - 1)) {
                nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
            }
            if ((i >= 0) && Character.isUpperCase(c)) {
                if (!upperCase || !nextUpperCase) {
                    if (i > 0) sb.append(SEPARATOR);
                }
                upperCase = true;
            } else {
                upperCase = false;
            }
            sb.append(Character.toLowerCase(c));
        }
        return sb.toString();
    }

    /**
     * 小驼峰
     *  user_name 变 userName
     *
     *  思路：就是解析诸葛字母，如果遇到下划线的时候，下个字母就变成大写的；
     */
    public static String toCamelCase(String s) {
        if (s == null) {
            return null;
        }
        s = s.toLowerCase();
        StringBuilder sb = new StringBuilder(s.length());
        boolean upperCase = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == SEPARATOR) {
                upperCase = true;
            } else if (upperCase) {
                sb.append(Character.toUpperCase(c));
                upperCase = false;
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 大驼峰
     * 即：小驼峰的首字母变成大写字母
     * user_name 变 UserName
     */
    public static String toCapitalizeCamelCase(String s) {
        if (null == s) {
            return null;
        }
        s = toCamelCase(s);
        return s.substring(0, 1).toUpperCase() + s.substring(1);
    }

    @Test
    public void test(){
        /*一般情况*/
        String userName = toUnderlineName("userName");  //userName  变 user_name
        System.out.println(userName);
        String user_name = toCamelCase("user_name");// user_name 变 userName
        System.out.println(user_name);
        String user_name1 = toCapitalizeCamelCase("user_name"); // user_name 变 UserName
        System.out.println(user_name1);
        /*特殊场景*/
        String userName1 = toUnderlineName("userNName");  //userNName  变 user_n_name
        System.out.println(userName1);
        String user_name22 = toCamelCase("user_n_ame");// user_n_ame 变 userNAme
        System.out.println(user_name22);
        String user_name222 = toCapitalizeCamelCase("user_n_ame"); // user_n_ame 变 UserNAme
        System.out.println(user_name222);

    }

}
